// pages/userInfoModify/userInfoModify.js
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 基本信息
    avatar: "",
    username: '',
    gender: "",
    age: undefined,
    height: undefined,
    weight: undefined,
    type_of_diabetes: '',


    // 页面控制信息
    ageError: false,

    genders: [{
        label: "男",
        value: "1"
      },
      {
        label: "女",
        value: "2"
      }
    ],
    genderVisible: false,

    types_of_diabetes: [{
        label: "一型糖尿病",
        value: "T1DM"
      },
      {
        label: "二型糖尿病",
        value: "T2DM"
      }
    ],
    type_of_diabetesVisible: false,

    infoChanged: false,
  },

  // 上传头像
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    this.uploadFile(avatarUrl)
  },
  uploadFile(tempFilePath) {
    console.log("upload begin", tempFilePath);
    const fs = wx.getFileSystemManager()

    fs.getFileInfo({
      filePath: tempFilePath,
      success: (res) => {
        console.log("file info", res.size); // 获取文件大小
        const fileSize = res.size;
        const ab = new ArrayBuffer(fileSize); // 使用文件大小来初始化 ArrayBuffer

        // 打开文件
        fs.open({
          filePath: tempFilePath,
          flag: 'r',
          success: (openRes) => {
            console.log("open file successfully", openRes);
            fs.read({
              fd: openRes.fd,
              arrayBuffer: ab,
              length: fileSize, // 使用文件大小作为长度
              success: (readRes) => {
                console.log("read successfully", readRes);
                wx.request({ // 调用接口
                  url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/files/upload?Name=avatar`,
                  method: 'POST',
                  header: {
                    "Content-Type": "image/jpeg",
                    "x-api-key": wx.getStorageSync('token')
                  },
                  data: ab,
                  success: (uploadRes) => { // 接口调用成功，获取token并缓存
                    if (uploadRes.statusCode == 200) {
                      const avatarURL = `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/files/download?Sid=${uploadRes.data.message}`;
                      console.log("avatar upload successfully", avatarURL);
                      this.setData({
                        avatar: avatarURL
                      })
                    } else {
                      console.log("upload unsuccessfully");
                    }
                  },
                  fail() {
                    console.log("upload unsuccessfully");
                  }
                });
              },
              fail(res) {
                console.log("read failed", res);
              }
            })
          },
          fail: (openFailRes) => {
            console.log("open file failed", openFailRes);
          }
        });
      },
      fail: (infoFailRes) => {
        console.log("get file info failed", infoFailRes);
      }
    });
  },



  // 保存用户信息
  saveInfo() {
    const userInfo = {
      username: this.data.username,
      avatar: this.data.avatar,
    }
    const userInfoDetail = {
      gender: parseFloat(this.data.gender),
      height: parseFloat(this.data.height),
      weight: parseFloat(this.data.weight),
      age: parseFloat(this.data.age),
      type_of_diabetes: this.data.type_of_diabetes,
    }
    console.log('userInfo', userInfo)
    console.log('userInfoDetail', userInfoDetail)
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=UpdateUserInfo`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      data: userInfo,
      success: (res) => {
        console.log("save userInfo successfully", res)
        wx.request({
          url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user_detail?Action=UpdateUserDetail`,
          method: 'POST',
          header: {
            "Content-Type": "application/json",
            "x-api-key": wx.getStorageSync('token')
          },
          data: userInfoDetail,
          success: (res) => {
            console.log("save userInfoDetail successfully", res)
            this.getUserInfo();

          }
        })
      }
    })
  },

  getUserInfo() {
    console.log('acquiring user info');
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=GetUserInfo`,
      method: 'GET',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      success(res) {
        console.log("fetched user info successfully", res);
        wx.setStorageSync('userInfo', res.data.message);
        wx.navigateBack();
      },
      fail(res) {
        console.log("fetch user info failed", res);
      }
    })
  },

  // 打开选择器
  showPicker(e) {
    console.log("showPicker");
    const {
      mode
    } = e.currentTarget.dataset;
    console.log(mode);
    this.setData({
      [`${mode}Visible`]: true,
    });
  },
  // 关闭选择器
  hidePicker() {
    const {
      mode
    } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  // 切换事件
  onConfirm(e) {
    const {
      mode
    } = e.currentTarget.dataset;
    this.setData({
      [mode]: e?.detail?.value[0],
    });

    this.hidePicker();
  },
  // 确认事件
  onColumnChange(e) {
    console.log('pick', e?.detail?.value[0]);
  },

  // 检查输入是否合理
  validateInputFormat(mode, input) {
    const trimmedInput = input.trim(); // 去除首尾空格

    // 检查输入是否为空
    if (!trimmedInput) {
      return false;
    }

    switch (mode) {
      case 'age':
      case 'height':
      case 'weight':
        // 检查输入是否为数字
        if (isNaN(trimmedInput)) {
          return false;
        }
        const numericValue = parseFloat(trimmedInput);
        // 对于age的合理范围
        if (mode === 'age' && (numericValue < 0 || numericValue > 150)) {
          return false;
        }
        // 对于height和weight可以根据具体需求调整合理范围
        if (mode === 'height' && (numericValue < 0.5 || numericValue > 2.5)) {
          return false;
        }
        if (mode === 'weight' && (numericValue < 20 || numericValue > 500)) {
          return false;
        }
        return true;

      case 'username':
        // 检查用户名是否包含非法字符，可以根据具体需求自定义正则表达式
        const usernameRegex = /^[a-zA-Z0-9_\u4e00-\u9fa5]{3,20}$/; // 只允许字母、数字、下划线和中文字符，长度为3到20
        return usernameRegex.test(trimmedInput);

      default:
        return false;
    }
  },

  // 处理输入操作
  handleInput(e) {
    const {
      mode
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;

    if (this.validateInputFormat(mode, value)) {
      this.setData({
        [mode]: value, // 将用户输入的内容保存到 data 中
        [`${mode}Error`]: false // 清除错误标志
      });
    } else {
      this.setData({
        [`${mode}Error`]: true // 设置错误标志为true
      });
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log('用户信息',wx.getStorageSync('userInfo'));
    const {
      username,
      avatar,
      gender,
      height,
      weight,
      age,
      type_of_diabetes
    } = wx.getStorageSync('userInfo');
    this.setData({
      username,
      avatar,
      gender,
      height,
      weight,
      age,
      type_of_diabetes
    })
    console.log(this.data.avatar)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})